package nio.Bchannel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 帅小伙
 * @date 2022/1/14
 * @description
 * 将数据写入文件
 */
public class FileChannel01 {


    public static void main(String[] args) throws Exception {
        String str = "hello ah";

        // 创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("file1.txt");
        // 通过fileOutputStream获取文件channel
        // fileChannel   真实类型是FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        // 创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 将数据放入buffer
        byteBuffer.put(str.getBytes());

        // 对bytebuffer 反转
        byteBuffer.flip();

        // 将bytebuffer  数据写入 channel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();

    }
}
